#! /usr/bin/env python
# -*- coding: utf-8 -*-
import hashlib
import time

from conf import setting


def auth_check():
    """
    和API验证
    :return:
    """
    ctime = time.time()
    key = setting.APIKEY
    dynamic_key = "{0}|{1}".format(key, ctime)
    m = hashlib.md5()
    m.update(bytes(dynamic_key, encoding='utf-8'))
    md5_key = m.hexdigest()
    md5_dynamic_key = "{0}|{1}".format(md5_key, ctime)

    return md5_dynamic_key


def decryption(client_md5_time_key, api_key_record):
    client_md5_key, client_ctime = client_md5_time_key.split('|')
    client_ctime = float(client_ctime)
    server_time = time.time()

    if server_time - client_ctime > 10:
        return False

    key = setting.AUTH_KEY
    server_dynamic_key = "{0}|{1}".format(key, client_ctime)
    m = hashlib.md5()
    m.update(bytes(server_dynamic_key, encoding='utf-8'))
    server_md5_key = m.hexdigest()
    if server_md5_key != client_md5_key:
        return False

    for key in list(api_key_record.keys()):
        v = api_key_record[key]
        if server_time > v:
            del api_key_record[key]

    if client_md5_time_key in api_key_record:
        return False
    else:
        api_key_record[client_md5_time_key] = client_ctime + 10
    return True
